function basePath() {
    var curWwwPath = window.document.location.href;
    var pathName = window.document.location.pathname;
    var pos = curWwwPath.indexOf(pathName);
    var localhostPath = curWwwPath.substring(0, pos);
    var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
    return (localhostPath + projectName);
}


loading();

$(function () {
    getClassList(1);
    validatorU();
    validatorA();
    $("#add_class_btn").click(function () {
        add();
    });
    $("#update_class_btn").click(function () {
        update();
    });

});


function validatorU() {
    $('#updateForm').bootstrapValidator({
        message: 'is not valid',
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            newClassName: {
                message: 'this is not valid',
                validators: {
                    notEmpty: {
                        message: '方向名不能为空'
                    },
                    stringLength: {
                        min: 2,
                        max: 5,
                        message: '方向名长度应该为2-5'
                    },
                    regexp: {
                        regexp: /^(?=[0-9a-zA-Z\u4e00-\u9fa5]+$)/,
                        message: '方向名只能由中文，数字和英文字母组成'
                    },
                    different: {
                        field: '22',
                        message: '方向名已存在'
                    }
                }
            }
        }
    });
}

function validatorA() {
    $('#addForm').bootstrapValidator({
        message: 'is not valid',
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            className1: {
                message: 'this is not valid',
                validators: {
                    notEmpty: {
                        message: '方向名不能为空'
                    },
                    stringLength: {
                        min: 2,
                        max: 5,
                        message: '方向名长度应该为2-5'
                    },
                    regexp: {
                        regexp: /^(?=[0-9a-zA-Z\u4e00-\u9fa5]+$)/,
                        message: '方向名只能由中文，数字和英文字母组成'
                    },
                    different: {
                        field: '22',
                        message: '方向名已存在'
                    }
                }
            }
        }
    });
}

var page_now = 1;
var max_page = 0;

function getClassList(page_num) {
    page_now = page_num;
    $.ajax({
        url: basePath() + '/edu/direction/get_direction.do',
        type: 'GET',
        async: 'true',
        data: {
            "pageNum": page_num,
            "pageSize": "10"
        },
        dataType: 'json',
        success: function (data) {
            removeLoading();
            var page = data.data;
            var item = data.data.list;
            max_page = page.pages;
            setPage(page.pageNum, page.pages, "getClassList");
            $("#result").html("");
            for (var i = 0; i < item.length; i++) {
                var temp = $("#m_template").clone();
                temp.attr("id", item[i].id);
                temp.removeAttr("style");
                temp.find(".c_num").html(page.pageSize * (page.pageNum - 1) + 1 + i);
                temp.find(".c_name").html(item[i].name);
                //修改按钮组装
                var up_btn = "<button type='button'  class='btn btn-xs btn-warning' onclick='toModal(this);' ><span class='glyphicon glyphicon-edit' aria-hidden='true'></span><span style='margin: 0px 8px;'>修改</span></button>"
                temp.find(".c_update").html(up_btn);
                //删除按钮组装
                var del_btn = "<button type='button'  class='btn btn-xs btn-danger' onclick='doDelete(" + item[i].id + ");' ><span class='glyphicon glyphicon-remove' aria-hidden='true'></span><span style='margin: 0px 8px;'>删除</span></button>"
                temp.find(".c_op").html(del_btn);
                //操作按钮组装
                var op_btn = "";
                if (item[i].spare == "1") {
                    $.ajax({
                        url: basePath()+'/edu/direction/get_conn_class.do',
                        type: 'post',
                        async: false,
                        data: {'directionId':item[i].id},
                        dataType: 'json',
                        success: function (res) {
                            op_btn = "<button id='tooltipBtn" + item[i].id + "' type='button' data-toggle='tooltip' data-placement='bottom' " +
                                " title='"+ res.msg +"' data-html='true' class='btn btn-xs btn-danger' onclick='doOperationClose(" + item[i].id + ");' ><span class='glyphicon glyphicon-remove-circle' aria-hidden='true'></span><span style='margin: 0px 8px;'>关闭</span></button>"
                            temp.find(".c_operation").html(op_btn);
                        }
                    });

                } else {
                    op_btn = "<button type='button' class='btn btn-xs btn-success' onclick='doOperationOpen(" + item[i].id + ");' ><span class='glyphicon glyphicon-ok-circle' aria-hidden='true'></span><span style='margin: 0px 8px;'>开启</span></button>";
                    temp.find(".c_operation").html(op_btn);
                }

                $("#result").append(temp);
            }
            $('[data-toggle="tooltip"]').tooltip();
        }
    })
}

function doOperationClose(id) {
    $.ajax({
        url: basePath() + "/edu/direction/close_direction.do",
        type: 'post',
        data: {'directionId': id},
        dataType: 'json',
        success: function (res) {
            if (res.success) {
                bootbox.alert(res.msg);
                getClassList(page_now);
            } else {
                bootbox.alert(res.msg);
            }
        }
    });
}

function doOperationOpen(id) {
    $.ajax({
        url: basePath() + '/edu/class/list_by_type.do',
        type: 'get',
        data: {'direction': id},
        dataType: 'json',
        success: function (res) {

            if (res.success) {
                $('#class').empty();
                $('#directionId').val(id);
                $.each(res.data, function (index, item) {
                    var op = "<option value='" + item.id + "'>" + item.name + "</option>";
                    $('#class').append(op);
                });
                $('#changeStatusModal').modal('show');
            } else {
                bootbox.alert(res.msg);
            }
        }
    });
}


function doOperationOpenSubmit() {
    var directionId = $('#directionId').val();
    var classId = $('#class').val();

    $.ajax({
        url: basePath() + "/edu/direction/open_direction.do",
        type: 'post',
        data: {'directionId': directionId, 'classId': classId},
        dataType: 'json',
        success: function (res) {
            if (res.success) {
                bootbox.alert(res.msg);
                getClassList(page_now);
                clearStatusModal();
            } else {
                bootbox.alert(res.msg);
            }
        }
    });

}

function doDelete(id) {
    bootbox.confirm({
        message: "确认删除吗?",
        buttons: {
            confirm: {
                label: '确定',
                className: 'btn-danger'
            },
            cancel: {
                label: '取消',
                className: 'btn-default'
            }
        },
        callback: function (result) {
            if (result) {
                $.ajax({
                    url: basePath() + '/edu/direction/delete_by_pk.do',
                    type: 'post',
                    data: {"id": id},
                    dataType: 'json',
                    success: function (res) {
                        if (res.success) {
                            bootbox.alert(res.msg);
                            getClassList(page_now);
                        } else {
                            bootbox.alert(res.msg);
                        }
                    }
                });
            }
        }
    });
}

function add() {

    // 提交前先主动验证表单
    var bv = $("#addForm").data('bootstrapValidator');
    bv.validate();
    if (!bv.isValid()) {
        return;
    }

    var name = $("#className1").val();
    $.ajax({
        url: basePath() + '/edu/direction/add_direction.do',
        type: 'POST',
        async: 'true',
        data: {
            "name": name,
        },
        dataType: 'json',
        success: function (res) {
            if (res.success) {
                clearAddModal();
                bootbox.alert(res.msg);
                getClassList(max_page);
            } else {
                if (res.msg == "ERROR") {
                    $('#addForm').data('bootstrapValidator').updateStatus('className1', 'INVALID', 'different');
                } else {
                    bootbox.alert(res.msg);
                }
            }

        }
    })
}

function clearAddModal() {
    $('#addClass').modal('hide');
    $('#className1').val("");
    $('#classContent').val("");

    $('#addForm').data('bootstrapValidator').destroy();
    $('#addForm').data('bootstrapValidator', null);
    $("form[id='addForm'] > div").addClass('has-success');
    validatorA();
}

//更新方向
function update() {
    // 提交前先主动验证表单
    var bv = $("#updateForm").data('bootstrapValidator');
    bv.validate();
    if (!bv.isValid()) {
        return;
    }

    var new_content = $("#newClassName").val();
    var id = $("#hello").val();
    $.ajax({
        url: basePath() + '/edu/direction/update_direction_name.do',
        type: 'POST',
        async: 'true',
        data: {
            "name": new_content,
            "id": id
        },
        dataType: 'json',
        success: function (res) {
            if (res.success) {
                bootbox.alert(res.msg);
                clearUpdateModal();
                getClassList(page_now);
            } else {
                if (res.msg == "ERROR") {
                    $('#updateForm').data('bootstrapValidator').updateStatus('newClassName', 'INVALID', 'different');
                } else {
                    bootbox.alert(res.msg);
                }
            }
        }
    })
}

function clearUpdateModal() {
    $('#changClass').modal('hide');
    $('#newClassName').val("");

    $('#updateForm').data('bootstrapValidator').destroy();
    $('#updateForm').data('bootstrapValidator', null);
    $("form[id='updateForm'] > div").addClass('has-success');
    validatorU();
}

function clearStatusModal() {
    $('#changeStatusModal').modal('hide');
}

function toModal(what) {
    var c_id = $(what).parent().parent().attr("id");
    $("#hello").val(c_id);
    $("#changClass").modal("show");
}